package com.audaque.springboot.foshanupload.core.scope;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;


/**
 * @author zgb
 * @desc ...
 *  同一个线程中从spring容器获取到的bean都是同一个对象
 * 使用方式： @Scope("threadLocalScope")
 * @date 2022-01-26 00:14:46
 */
public class ThreadLocalScope implements Scope {
    private static final TransmittableThreadLocal<Object> THREAD_LOCAL = new TransmittableThreadLocal<>();



    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Object value = THREAD_LOCAL.get();
        if (value != null) {
            return value;
        }

        Object object = objectFactory.getObject();
        THREAD_LOCAL.set(object);
        return object;
    }

    @Override
    public Object remove(String name) {
        THREAD_LOCAL.remove();
        return null;
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {

    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}
